package uriel.frankel;

import java.util.ArrayList;

import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;




import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

public class TestMyGoogleAppEngineActivity extends Activity implements
		OnClickListener {
	private static final String GAE_URL = "http://urielfra.appspot.com/testgae";
	private Button mButton;
	private EditText mSalaryEditText;
	private EditText mCompanyEditText;
	private EditText mSeniorityEditText;
	private EditText mJobTitleEditText;
	private EditText mDisiplineEditText;
	private HttpClient mHttpClient;
	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		startActivity(new Intent(this, PollHelper.class));
		setContentView(R.layout.salary_poll_layout);
		Bundle extras = getIntent().getExtras();
		if(extras!=null){
			mHttpClient = extras.getParcelable("mock");
		}
		mButton = (Button) findViewById(R.id.send_button);
		mButton.setOnClickListener(this);

		mSalaryEditText = (EditText) findViewById(R.id.salary_edit_text);
		mCompanyEditText = (EditText) findViewById(R.id.company_edit_text);
		mSeniorityEditText = (EditText) findViewById(R.id.seniority_edit_text);
		mJobTitleEditText = (EditText) findViewById(R.id.job_title_edit_text);
		mDisiplineEditText = (EditText) findViewById(R.id.disipline_edit_text);
	}

	@Override
	public void onClick(View v) {
		mButton.setEnabled(false);
		boolean allSet = true;
		
		String errorMsg = "בבקשה הכנס:\n";
		final String salaryAsString = mSalaryEditText.getText().toString();
		final String companyAsString = mCompanyEditText.getText().toString();
		final String seniorityAsString = mSeniorityEditText.getText()
				.toString();
		final String disiplineAsString = mDisiplineEditText.getText()
				.toString();
		final String jobTitleAsString = mJobTitleEditText.getText().toString();

		if (salaryAsString == null || salaryAsString.length() ==0) {
			allSet = false;
			errorMsg += "משכורת\n";
		}
		if(jobTitleAsString == null || jobTitleAsString.length()==0){
			allSet = false;
			errorMsg += "העבודה\n";
		}
		if (companyAsString == null || companyAsString.length() == 0) {
			allSet = false;
			errorMsg += "שם חברה (או עצמאי)\n";
		}
		if (disiplineAsString == null || disiplineAsString.length() == 0) {
			allSet = false;
			errorMsg += "תחום\n";
		}
		if (seniorityAsString == null || seniorityAsString.length() == 0) {
			allSet = false;
			errorMsg += "וותק";
		}
		final String errorMsgHolder = errorMsg;
		if(allSet==false){
			runOnUiThread(new Runnable() {
				public void run() {
					Toast.makeText(getApplicationContext(),
									errorMsgHolder, Toast.LENGTH_LONG).show();
							
				}
			});
			mButton.setEnabled(true);
			return;
		}
		
		Thread thread = new Thread(new Runnable() {

			

			@Override
			public void run() {

				HttpParams httpParameters = new BasicHttpParams();
				// Set the timeout in milliseconds until a connection is
				// established.
				// The default value is zero, that means the timeout is not
				// used.
				int timeoutConnection = 5000;
				HttpConnectionParams.setConnectionTimeout(httpParameters,
						timeoutConnection);
				// Set the default socket timeout (SO_TIMEOUT)
				// in milliseconds which is the timeout for waiting for data.
				int timeoutSocket = 5000;
				HttpConnectionParams
						.setSoTimeout(httpParameters, timeoutSocket);
				if(mHttpClient==null){
					mHttpClient = new DefaultHttpClient(httpParameters);
				}

				HttpPost request;

				request = new HttpPost(GAE_URL);

				String toastMessage = "סליחה, אבל קרתה תקלה כלשהי והמשכורת לא נשלחה";
				try {

					ArrayList<NameValuePair> postParameters = new ArrayList<NameValuePair>();
					postParameters.add(new BasicNameValuePair("salary",
							salaryAsString));
					postParameters.add(new BasicNameValuePair("seniority",
							seniorityAsString));
					postParameters.add(new BasicNameValuePair("jobTitle",
							jobTitleAsString));
					postParameters.add(new BasicNameValuePair("company",
							companyAsString));
					postParameters.add(new BasicNameValuePair("discipline",
							disiplineAsString));
					UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(
							postParameters, "UTF-8");
					request.setEntity(formEntity);
					final HttpResponse response = mHttpClient.execute(request);

					if (response.getStatusLine().getStatusCode() == 200) {
						toastMessage = "תודה שהשתתפת בסקר";
					}

					Log.i("Uriel", response.toString());
				} catch (Exception e) {
					toastMessage = "סליחה, אבל קרתה תקלה כלשהי והמשכורת לא נשלחה";
					Log.e("Uriel", e == null ? "unknown" : e.getMessage());
				} finally {
					final String stringToShow = toastMessage;// hack for final
																// issues
					runOnUiThread(new Runnable() {
						public void run() {
							Toast.makeText(getApplicationContext(),
									stringToShow, Toast.LENGTH_LONG).show();
							finish();

						}
					});
				}

			}
		});
		thread.start();
	}
}